{% extends "layout.html" %}

{% block title %}首页 - 智能分析系统{% endblock %}

{% block content %}
<div class="finance-portal-container">
    <!-- 左侧导航栏 -->
    <div class="portal-sidebar">
        <div class="sidebar-menu">
            <div class="sidebar-header">
                <h5><i class="fas fa-th-list"></i> 功能导航</h5>
            </div>
            <div class="sidebar-content">
                <ul class="sidebar-nav">
                    <li><a href="/dashboard"><i class="fas fa-chart-line"></i> 智能仪表盘</a></li>
                    <li><a href="/fundamental"><i class="fas fa-file-invoice-dollar"></i> 基本面分析</a></li>
                    <li><a href="/capital_flow"><i class="fas fa-money-bill-wave"></i> 资金流向</a></li>
                    <li><a href="/market_scan"><i class="fas fa-search"></i> 市场扫描</a></li>
                    <li><a href="/scenario_predict"><i class="fas fa-lightbulb"></i> 情景预测</a></li>
                    <li><a href="/portfolio"><i class="fas fa-briefcase"></i> 投资组合</a></li>
                    <li><a href="/qa"><i class="fas fa-question-circle"></i> 智能问答</a></li>
                    <li><a href="/risk_monitor"><i class="fas fa-exclamation-triangle"></i> 风险监控</a></li>
                    <li><a href="/industry_analysis"><i class="fas fa-industry"></i> 行业分析</a></li>
                </ul>
            </div>
        </div>

<!--        <div class="quick-search mt-4">-->
<!--            <div class="card">-->
<!--                <div class="card-header">-->
<!--                    <h5 class="mb-0"><i class="fas fa-search"></i> 快速分析</h5>-->
<!--                </div>-->
<!--                <div class="card-body">-->
<!--                    <form id="quick-analysis-form">-->
<!--                        <div class="mb-3">-->
<!--                            <label for="quick-stock-code" class="form-label">股票代码</label>-->
<!--                            <input type="text" class="form-control" id="quick-stock-code" placeholder="例如: 600519">-->
<!--                        </div>-->
<!--                        <div class="mb-3">-->
<!--                            <label for="quick-market-type" class="form-label">市场类型</label>-->
<!--                            <select class="form-select" id="quick-market-type">-->
<!--                                <option value="A" selected>A股</option>-->
<!--                                <option value="HK">港股</option>-->
<!--                                <option value="US">美股</option>-->
<!--                            </select>-->
<!--                        </div>-->
<!--                        <div class="d-grid">-->
<!--                            <button type="button" class="btn btn-primary" id="quick-analysis-btn">开始分析</button>-->
<!--                        </div>-->
<!--                    </form>-->
<!--                </div>-->
<!--            </div>-->
<!--        </div>-->
    </div>

    <!-- 中间新闻区域 -->
    <div class="portal-news">
        <div class="news-header">
            <h5><i class="fas fa-newspaper"></i> 实时快讯（来源：财联社）</h5>
            <div class="news-tools">
                <button class="btn btn-sm btn-outline-primary refresh-news-btn">
                    <i class="fas fa-sync-alt"></i>
                </button>
                <div class="form-check form-check-inline ms-2">
                    <input class="form-check-input" type="checkbox" id="only-important">
                    <label class="form-check-label" for="only-important">只看重要</label>
                </div>
            </div>
        </div>
        <div class="news-content" id="news-timeline">
            <div class="text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">加载新闻中...</p>
            </div>
        </div>
    </div>

    <!-- 右侧热点区域 -->
    <div class="portal-hotspot">
        <div class="hotspot-header">
            <h5><i class="fas fa-fire"></i> 热点</h5>
        </div>
        <div class="hotspot-content" id="hotspot-list">
            <div class="text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">加载热点中...</p>
            </div>
        </div>
    </div>

    <!-- 页脚固定区域 -->
    <div class="portal-footer">
        <!-- 页脚市场状态部分 -->
        <div class="market-status">
            <div class="market-group">
                <div class="group-title">亚太市场</div>
                <div class="status-group">
                    <div class="status-item" id="china-market">
                        <i class="fas fa-circle"></i> A股
                        <span class="status-text">加载中...</span>
                    </div>
                    <div class="status-item" id="hk-market">
                        <i class="fas fa-circle"></i> 港股
                        <span class="status-text">加载中...</span>
                    </div>
                    <div class="status-item" id="taiwan-market">
                        <i class="fas fa-circle"></i> MSCI中国台湾
                        <span class="status-text">加载中...</span>
                    </div>
                    <div class="status-item" id="japan-market">
                        <i class="fas fa-circle"></i> 日经225
                        <span class="status-text">加载中...</span>
                    </div>
                </div>
            </div>

            <div class="market-group">
                <div class="group-title">欧非中东</div>
                <div class="status-group">
                    <div class="status-item" id="uk-market">
                        <i class="fas fa-circle"></i> 富时100
                        <span class="status-text">加载中...</span>
                    </div>
                    <div class="status-item" id="german-market">
                        <i class="fas fa-circle"></i> 德国DAX
                        <span class="status-text">加载中...</span>
                    </div>
                    <div class="status-item" id="france-market">
                        <i class="fas fa-circle"></i> 法国MOEX
                        <span class="status-text">加载中...</span>
                    </div>
                </div>
            </div>

            <div class="market-group">
                <div class="group-title">美洲市场</div>
                <div class="status-group">
                    <div class="status-item" id="us-market">
                        <i class="fas fa-circle"></i> 美股
                        <span class="status-text">加载中...</span>
                    </div>
                    <div class="status-item" id="nasdaq-market">
                        <i class="fas fa-circle"></i> 纳指
                        <span class="status-text">加载中...</span>
                    </div>
                    <div class="status-item" id="brazil-market">
                        <i class="fas fa-circle"></i> 巴西
                        <span class="status-text">加载中...</span>
                    </div>
                </div>
            </div>

            <div class="current-time" id="current-time">
                当前时间: <span>{{ current_time }}</span>
                <span class="refresh-time" id="refresh-time">刷新: 5:00</span>
            </div>
        </div>
        <div class="ticker-news" id="ticker-container">
            <div class="ticker-wrapper">
                <div class="ticker-item">最新消息加载中...</div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
$(document).ready(function() {
    // 快速分析按钮点击事件
    $('#quick-analysis-btn').click(function() {
        const stockCode = $('#quick-stock-code').val().trim();
        const marketType = $('#quick-market-type').val();

        if (!stockCode) {
            alert('请输入股票代码');
            return;
        }

        // 跳转到股票详情页
        window.location.href = `/stock_detail/${stockCode}?market_type=${marketType}`;
    });

    // 回车键提交表单
    $('#quick-stock-code').keypress(function(e) {
        if (e.which === 13) {
            $('#quick-analysis-btn').click();
            return false;
        }
    });

    // 加载最新新闻
    loadLatestNews();

    // 加载舆情热点
    loadHotspots();

    // 更新市场状态
    updateMarketStatus();

    // 启动滚动新闻
    startTickerNews();

    // 刷新按钮点击事件
    $('.refresh-news-btn').click(function() {
        loadLatestNews();
    });

    // 只看重要切换事件
    $('#only-important').change(function() {
        loadLatestNews();
    });

    // 定时刷新
    setInterval(function() {
        updateMarketStatus();
        // 每5分钟自动刷新新闻
        loadLatestNews(true); // 静默刷新
        startTickerNews();
    }, 300000); // 5分钟

    // 每秒更新当前时间
    setInterval(function() {
        updateCurrentTime();
    }, 1000);

    // 每秒更新一次时间和倒计时
    setInterval(function() {
        updateCurrentTime();
        updateRefreshCountdown();
    }, 1000);


});

// 加载最新新闻函数
function loadLatestNews(silent = false) {
    if (!silent) {
        $('#news-timeline').html(`
            <div class="text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">加载新闻中...</p>
            </div>
        `);
    }

    const onlyImportant = $('#only-important').is(':checked');

    $.ajax({
        url: '/api/latest_news',
        method: 'GET',
        data: {
            days: 2,
            limit: 500,
            important: onlyImportant ? 1 : 0
        },
        success: function(response) {
            if (response.success && response.news && response.news.length > 0) {
                displayNewsTimeline(response.news);
            } else {
                if (!silent) {
                    $('#news-timeline').html('<div class="alert alert-info">暂无最新新闻</div>');
                }
            }
        },
        error: function(err) {
            console.error('获取新闻失败:', err);
            if (!silent) {
                $('#news-timeline').html('<div class="alert alert-danger">获取新闻失败，请稍后重试</div>');
            }
        }
    });
}

// 加载舆情热点函数
function loadHotspots() {
    $('#hotspot-list').html(`
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">加载热点中...</p>
        </div>
    `);

    $.ajax({
        url: '/api/latest_news',
        method: 'GET',
        data: {
            days: 1,
            limit: 10,
            type: 'hotspot'
        },
        success: function(response) {
            if (response.success && response.news && response.news.length > 0) {
                displayHotspots(response.news);
            } else {
                $('#hotspot-list').html('<div class="alert alert-info">暂无舆情热点</div>');
            }
        },
        error: function(err) {
            console.error('获取热点失败:', err);
            $('#hotspot-list').html('<div class="alert alert-danger">获取热点失败，请稍后重试</div>');
        }
    });
}

// 显示热点列表
function displayHotspots(hotspots) {
    if (hotspots.length === 0) {
        $('#hotspot-list').html('<div class="alert alert-info">暂无舆情热点</div>');
        return;
    }

    let hotspotsHtml = '<div class="hotspot-list">';

    hotspots.forEach((item, index) => {
        const rankClass = index < 3 ? 'rank-top' : '';
        hotspotsHtml += `
            <div class="hotspot-item">
                <span class="hotspot-rank ${rankClass}">${index + 1}</span>
                <span class="hotspot-title">${item.title || item.content}</span>
            </div>
        `;
    });

    hotspotsHtml += '</div>';

    $('#hotspot-list').html(hotspotsHtml);
}

// 替换现有的displayNewsTimeline函数
function displayNewsTimeline(newsList) {
    if (newsList.length === 0) {
        $('#news-timeline').html('<div class="alert alert-info">暂无新闻</div>');
        return;
    }
    
    let timelineHtml = '<div class="news-timeline-container">';
    
    // 首先按完整的日期时间排序，确保最新消息在最前面
    newsList.sort((a, b) => {
        // 构建完整的日期时间字符串 (YYYY-MM-DD HH:MM)
        const dateTimeA = (a.date || '') + ' ' + (a.time || '00:00');
        const dateTimeB = (b.date || '') + ' ' + (b.time || '00:00');
        
        // 转换为Date对象进行比较
        const timeA = new Date(dateTimeA);
        const timeB = new Date(dateTimeB);
        
        // 返回降序结果（最新的在前）
        return timeB - timeA;
    });
    
    // 按天和时间点分组
    const newsGroups = {};
    newsList.forEach(news => {
        // 创建格式为"YYYY-MM-DD HH:MM"的键
        const date = news.date || '';
        const time = news.time || '00:00';
        
        // 显示用的键：日期+时间
        const displayKey = `${date} ${time.substring(0, 5)}`;
        
        if (!newsGroups[displayKey]) {
            newsGroups[displayKey] = [];
        }
        newsGroups[displayKey].push(news);
    });
    
    // 获取并按时间降序排列所有组键
    const sortedKeys = Object.keys(newsGroups).sort((a, b) => {
        const timeA = new Date(a);
        const timeB = new Date(b);
        return timeB - timeA;
    });
    
    // 生成时间线HTML
    sortedKeys.forEach(displayKey => {
        const newsItems = newsGroups[displayKey];
        const parts = displayKey.split(' ');
        const date = parts[0];
        const time = parts[1];
        
        // 格式化显示日期（只在新的一天开始时显示）
        const formattedDate = formatDate(date);
        
        timelineHtml += `
            <div class="time-point">
                <div class="time-label">${time}</div>
                <div class="time-date">${formattedDate}</div>
                <div class="news-items">
        `;
        
        newsItems.forEach(news => {
            let contentClass = '';
            // 根据内容中是否含有特定关键词添加样式
            if (news.content && (news.content.includes('增长') || news.content.includes('上涨') || news.content.includes('利好'))) {
                contentClass = 'text-success';
            } else if (news.content && (news.content.includes('下跌') || news.content.includes('下降') || news.content.includes('利空'))) {
                contentClass = 'text-danger';
            }
            
            timelineHtml += `
                <div class="news-item">
                    <div class="news-content ${contentClass}">${news.content || ''}</div>
                </div>
            `;
        });
        
        timelineHtml += `
                </div>
            </div>
        `;
    });
    
    timelineHtml += '</div>';
    
    // 更新DOM
    $('#news-timeline').html(timelineHtml);
}

// 日期格式化辅助函数
function formatDate(dateStr) {
    // 检查是否与当天日期相同
    const today = new Date();
    const todayStr = today.toISOString().split('T')[0];
    
    if (dateStr === todayStr) {
        return '';
    }
    
    // 昨天
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    const yesterdayStr = yesterday.toISOString().split('T')[0];
    
    if (dateStr === yesterdayStr) {
        return '昨天';
    }
    
    // 其他日期用中文格式
    const date = new Date(dateStr);
    return `${date.getMonth() + 1}月${date.getDate()}日`;
}

// 添加页面自动刷新功能
let refreshCountdown = 300; // 5分钟倒计时（秒）

// 更新市场状态
function updateMarketStatus() {
    const now = new Date();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const weekday = now.getDay(); // 0为周日，6为周六

    // 检查是否为工作日
    const isWeekend = weekday === 0 || weekday === 6;

    // 亚太市场时区
    // A股状态 (9:30-11:30, 13:00-15:00)
    let chinaStatus = { open: false, text: '未开市' };
    if (!isWeekend && ((hours === 9 && minutes >= 30) || hours === 10 || (hours === 11 && minutes <= 30) ||
        (hours >= 13 && hours < 15))) {
        chinaStatus = { open: true, text: '交易中' };
    }

    // 港股状态 (9:30-12:00, 13:00-16:00)
    let hkStatus = { open: false, text: '未开市' };
    if (!isWeekend && ((hours === 9 && minutes >= 30) || hours === 10 || hours === 11 ||
        (hours >= 13 && hours < 16))) {
        hkStatus = { open: true, text: '交易中' };
    }

    // 台股状态 (9:00-13:30)
    let taiwanStatus = { open: false, text: '未开市' };
    if (!isWeekend && ((hours === 9) || hours === 10 || hours === 11 || hours === 12 ||
        (hours === 13 && minutes <= 30))) {
        taiwanStatus = { open: true, text: '交易中' };
    }

    // 日本股市 (9:00-11:30, 12:30-15:00)
    let japanStatus = { open: false, text: '未开市' };
    if (!isWeekend && ((hours === 9) || hours === 10 || (hours === 11 && minutes <= 30) ||
        (hours === 12 && minutes >= 30) || hours === 13 || hours === 14)) {
        japanStatus = { open: true, text: '交易中' };
    }

    // 欧洲市场 - 需要调整时区，这里是基于欧洲夏令时(UTC+2)与北京时间(UTC+8)相差6小时计算
    // 英国股市 (伦敦，北京时间15:00-23:30)
    let ukStatus = { open: false, text: '未开市' };
    if (!isWeekend && ((hours >= 15 && hours < 23) || (hours === 23 && minutes <= 30))) {
        ukStatus = { open: true, text: '交易中' };
    }

    // 德国股市 (法兰克福，北京时间15:00-23:30)
    let germanStatus = { open: false, text: '未开市' };
    if (!isWeekend && ((hours >= 15 && hours < 23) || (hours === 23 && minutes <= 30))) {
        germanStatus = { open: true, text: '交易中' };
    }

    // 法国股市 (巴黎，北京时间15:00-23:30)
    let franceStatus = { open: false, text: '未开市' };
    if (!isWeekend && ((hours >= 15 && hours < 23) || (hours === 23 && minutes <= 30))) {
        franceStatus = { open: true, text: '交易中' };
    }

    // 美洲市场
    // 美股状态 (纽约，北京时间21:30-4:00)
    let usStatus = { open: false, text: '未开市' };
    if ((hours >= 21 && minutes >= 30) || hours >= 22 || hours < 4) {
        // 检查美股的工作日 (当北京时间是周六早上，美国还是周五)
        const usDay = hours < 12 ? (weekday === 6 ? 5 : weekday - 1) : weekday;
        if (usDay !== 0 && usDay !== 6) {
            usStatus = { open: true, text: '交易中' };
        }
    }

    // 纳斯达克与美股相同
    let nasdaqStatus = usStatus;

    // 巴西股市 (圣保罗，北京时间20:30-3:00)
    let brazilStatus = { open: false, text: '未开市' };
    if ((hours >= 20 && minutes >= 30) || hours >= 21 || hours < 3) {
        const brazilDay = hours < 12 ? (weekday === 6 ? 5 : weekday - 1) : weekday;
        if (brazilDay !== 0 && brazilDay !== 6) {
            brazilStatus = { open: true, text: '交易中' };
        }
    }

    // 更新DOM
    updateMarketStatusUI('china-market', chinaStatus);
    updateMarketStatusUI('hk-market', hkStatus);
    updateMarketStatusUI('taiwan-market', taiwanStatus);
    updateMarketStatusUI('japan-market', japanStatus);

    updateMarketStatusUI('uk-market', ukStatus);
    updateMarketStatusUI('german-market', germanStatus);
    updateMarketStatusUI('france-market', franceStatus);

    updateMarketStatusUI('us-market', usStatus);
    updateMarketStatusUI('nasdaq-market', nasdaqStatus);
    updateMarketStatusUI('brazil-market', brazilStatus);
}

// 更新市场状态UI
function updateMarketStatusUI(elementId, status) {
    const element = $(`#${elementId}`);
    const iconElement = element.find('i');
    const textElement = element.find('.status-text');

    if (status.open) {
        iconElement.removeClass('status-closed').addClass('status-open');
    } else {
        iconElement.removeClass('status-open').addClass('status-closed');
    }

    textElement.text(status.text);
}

// 更新倒计时
function updateRefreshCountdown() {
    refreshCountdown--;

    if (refreshCountdown <= 0) {
        // 重新加载页面
        window.location.reload();
        return;
    }

    const minutes = Math.floor(refreshCountdown / 60);
    const seconds = refreshCountdown % 60;
    $('#refresh-time').text(`刷新: ${minutes}:${seconds < 10 ? '0' + seconds : seconds}`);
}

// 更新当前时间
function updateCurrentTime() {
    const now = new Date();
    const timeString = now.toLocaleTimeString('zh-CN', { hour12: false });
    $('#current-time span').text(timeString);
}

// 启动滚动新闻
function startTickerNews() {
    $.ajax({
        url: '/api/latest_news',
        method: 'GET',
        data: {
            days: 1,
            limit: 10
        },
        success: function(response) {
            if (response.success && response.news && response.news.length > 0) {
                displayTickerNews(response.news);
            } else {
                $('#ticker-container .ticker-wrapper').html('<div class="ticker-item">暂无最新消息</div>');
            }
        },
        error: function(err) {
            console.error('获取滚动新闻失败:', err);
            $('#ticker-container .ticker-wrapper').html('<div class="ticker-item">获取最新消息失败</div>');
        }
    });
}

// 显示滚动新闻
function displayTickerNews(newsList) {
    if (newsList.length === 0) {
        $('#ticker-container .ticker-wrapper').html('<div class="ticker-item">暂无最新消息</div>');
        return;
    }

    let tickerItems = '';

    newsList.forEach(news => {
        tickerItems += `<div class="ticker-item">${news.content || ''}</div>`;
    });

    $('#ticker-container .ticker-wrapper').html(tickerItems);

    // 启动滚动效果
    const tickerWidth = $('#ticker-container').width();
    const wrapper = $('#ticker-container .ticker-wrapper');

    wrapper.width(tickerWidth * 2);
    wrapper.css('animation', 'ticker 30s linear infinite');
}
</script>
{% endblock %}
